from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework_jwt.settings import api_settings
from rest_framework.generics import CreateAPIView
from django.conf import settings
from QQLoginTool.QQtool import OAuthQQ
from oauth.models import OAuthQQUser
from itsdangerous import TimedJSONWebSignatureSerializer as TJS
from oauth.serializers import OauthSerializer
# Create your views here.

class QQLoginURLView(APIView):
    '''构建跳转连接'''

    def get(self,request):
        state = request.query_params.get('next')
        if state is None:
            state = '/'
        # 1,生成qq对象
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI,state=state)

        # 调用生成url的方法
        login_url = qq.get_qq_url()

        # 返回url
        return Response({'login_url':login_url})


class OauthView(CreateAPIView):
    '''获取openid和绑定openid'''

    serializer_class = OauthSerializer
    def get(self,request):
        # 1,获取前端获取的数据
        code = request.query_params.get('code')
        if code is None:
            return Response({'errors':'缺少code值'},status=400)
        # 2,通过code值请求qq服务器获取access_token值
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI, state='/')
        access_token = qq.get_access_token(code)
        # 3,通过access_token值请求qq服务器获取openid值
        openid = qq.get_open_id(access_token=access_token)

        # 4,判断openid和美多用户是否绑定
        try:
            qq_user = OAuthQQUser.objects.get(openid=openid)
        except:
            #5, 未绑定，绑定openid
            # 密钥，过期时间
            tjs = TJS(settings.SECRET_KEY, 300)
            # 加密
            data = tjs.dumps({'openid':openid}).decode()

            return Response({'access_token':data})

        #6,如果绑定过则登录成功
        else:
            # 获取用户对象
            user = qq_user.user

            # 生成jwt token
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            return Response({

                'token': token,
                'username': user.username,
                'user_id': user.id
            })




